package site.wtcc.originalfavor.func.aop;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import site.wtcc.originalfavor.biz.Result;
import site.wtcc.originalfavor.func.utils.JsonUtil;

/**
 * Wrap the response of controller method to {@link site.wtcc.originalfavor.biz.Result} for protocol conformance.
 *
 * @author wangwei
 */
@Slf4j
@RestControllerAdvice(basePackages = {"site.wtcc.originalfavor.biz","site.wtcc.originalfavor.api"})
public class MyGlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType, @NotNull MediaType selectedContentType,
                                  @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {
        if (body instanceof Result) {
            return body;
        } else if (body instanceof String) {
            String stringBody = (String) body;
            Result<String> result = Result.ofData(stringBody);
            return JsonUtil.toJson(result).orElse("");
        } else {
            return Result.ofData(body);
        }
    }

}
